const jwt = require('jsonwebtoken')
const ok = require('../core/response-shortcut');
const CONFIG = require('../config/config');
const {aseDecode}=require('../core/crypto')


const createJWT = function (obj) {
    /*
     * 生成jwt并写入cookie
     * return {
    "msg": "success",
    "errorCode": 1,
    "data": {
        "jwt": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1aWQiOiIyMiIsIm5hbWUiOiLkuI3kuI3kuI0iLCJpYXQiOjE1NzE3MjU0MDIsImV4cCI6MTU3NDQwMzgwMn0.utEjMzAQrRL6HbpccNUeXUkbTfP1eDjmHdePXrBmj80"
    }
}
     */
   // let req = ctx.request.body;

    //data形如{"aa":123,"bb":"nba"}
    if (Object.prototype.toString.call(obj) !== '[object Object]') {
        throw new global.errs.ParameterException('必须传入JSON格式');
    }
    if (JSON.stringify(obj) === "{}") {
         throw new global.errs.ParameterException('post参数不能为空对象');
    }
let jwtStr = jwt.sign(obj, CONFIG.JWTSECRETKEY, {
    expiresIn: CONFIG.JWTEXPIRESIN
})
    return jwtStr
    //ctx.response.status = 200;
    //ctx.body = ok.json({ "jwt": jwtStr })
}



const verifyJWT = function (ctx) {
    /**
     * 经过secretkey验证后
     * 只返回decode之后的jwt值或报错终止程序
     * 正常返回形如:{id:'bssdasdbs45de',iat:1458562356,exp:1258635254}
     */
    //var jwtVal = ctx.cookies.get(CONFIG.COOKIEJWTNAME) || ''
    var jwtVal = ctx.header['access-token'] || ''
    if (jwtVal.indexOf('.') === -1) {
        throw new global.errs.ParameterException('jwt格式错误');
    }

    try {
        return jwt.verify(jwtVal, CONFIG.JWTSECRETKEY);
    } catch (err) {
        throw new global.errs.ParameterException('该jwt非己出或已被篡改');
    }


    /*    let res=await new Promise((resolve) => {
           jwt.verify(jwtVal, CONFIG.JWTSECRETKEY, function (err, data) {
              err?resolve(false):resolve(true)
               //这里的data已经是payload了
                if (err) {
                   switch (err.name) {
                       case 'TokenExpiredError':
                           throw new global.errs.Forbidden('jwtVal已过期');
                           break;
                       case 'JsonWebTokenError':
                           throw new global.errs.Forbidden('无效的jwt');
                           break;
                       default:
                           throw new global.errs.Forbidden(err.name);
                   }
               }

           })
       })
       return res; */
}

const getJWT = function (jwtStr) {
    /**
     * jwt.decode(jwtStr)该函数执行后,返回的就是掐头去尾的payload,形如{uid:12,name:"撒旦",iat:15485445,exp:12121212}
     * return payload
     */
    return jwt.decode(jwtStr);
}

const decodeJWTId = function (ctx) { 
    /*
     * return 解密后用户的id
     */
    var jwtStr=verifyJWT(ctx)
    return aseDecode(jwtStr.id)
}

module.exports = {
    createJWT, verifyJWT, getJWT,decodeJWTId
}
